//
//  CDHttpHelper.m
//  TextLogin
//
//  Created by 白航飞 on 16/5/12.
//  Copyright (c) 2016年 白航飞. All rights reserved.
//

#import "CDHttpHelper.h"
#import "AFNetworking.h"
#import "JSONKit.h"
#import <UIKit/UIKit.h>
#import "MBProgressHUD+Add.h"
@implementation CDHttpHelper

+ (CDHttpHelper *)defaultCDHttpHelper
{
    static CDHttpHelper *httpHelper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        httpHelper = [[CDHttpHelper alloc] init];
    });
    return httpHelper;
}
#pragma mark get数据请求
- (void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id responseObj))success failure:(void (^)(NSError *error))failure showHUD:(BOOL) Bool
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    session.responseSerializer = [AFHTTPResponseSerializer serializer];

    if (Bool == YES) {
        [MBProgressHUD showHUD];
    }
    [session GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
             [MBProgressHUD dissmiss];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        NSString *errorstr = nil;
        
        switch (error.code) {
            case -1004:
                errorstr = @"未能连接到服务器";
                break;
            case -1009:
                errorstr = @"似乎已断开与互联网的连接。";
                break;
            case -1001:
                errorstr = @"请求超时";
                break;
            default:
                errorstr = @"请求失败";
                break;
        }
        
        
        ZCAlertViewController *networkAlert = [ZCAlertViewController alertControllerWithTitle:nil message:errorstr];
        ZCAlertAction *netWorkAction = [ZCAlertAction actionWithTitle:@"确定" handler:^(ZCAlertAction *action) {
            
        }];
        [networkAlert addAction:netWorkAction];
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window.rootViewController presentViewController:networkAlert animated:YES completion:^{
            
        }];
        
        [MBProgressHUD dissmiss];
    }];
}
- (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id responseObj))success failure:(void (^)(NSError *error))failure showHUD:(BOOL) Bool
{
        //网络判断
    AFNetworkReachabilityManager *Manager= [AFNetworkReachabilityManager sharedManager];
    [Manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusNotReachable) {
            UIView  *view = (UIView*)[[[UIApplication sharedApplication]delegate]window];
            [MBProgressHUD showMessag:@"当前无网络,请检查网络设置" toView:view];
        }
        
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络");
                
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G|4G");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi");
                break;
            default:
                break;
        }
    }];
    
    [Manager startMonitoring];
    if (Bool == YES) {
        [MBProgressHUD showHUD];
    }
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
   
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
   
    
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    session.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    session.responseSerializer = [AFHTTPResponseSerializer serializer];

    [session POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);

            [MBProgressHUD dissmiss];
            
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
           failure(error);
            NSLog(@"%@",error);
            NSString *errorstr = nil;
            
            switch (error.code) {
                case -1004:
                    errorstr = @"未能连接到服务器";
                    break;
                case -1009:
                    errorstr = @"似乎已断开与互联网的连接。";
                    break;
                case -1001:
                    errorstr = @"请求超时";
                    break;
                default:
                    errorstr = @"请求失败";
                    break;
            }
            
            
            ZCAlertViewController *networkAlert = [ZCAlertViewController alertControllerWithTitle:nil message:errorstr];
            ZCAlertAction *netWorkAction = [ZCAlertAction actionWithTitle:@"确定" handler:^(ZCAlertAction *action) {
                
            }];
            [networkAlert addAction:netWorkAction];
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            [window.rootViewController presentViewController:networkAlert animated:YES completion:^{
                
            }];

            [MBProgressHUD dissmiss];
        }
    }];
}
-(void)sendReportInfo:(NSString *)url andData:(NSData *)data
{
    NSURL *urlData = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlData cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSInputStream *inputStream = [NSInputStream inputStreamWithData:data];
    [request setHTTPBodyStream:inputStream];
    __weak CDHttpHelper *http = self;
    NSURLSession *session = [NSURLSession sharedSession];
    [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil) {
            NSLog(@"------99999999%@",error);
            return;
        }
        else{
            http.backBlock(data);
        }

    }];
    }
- (void)sendReportInfo:(NSString *)url andData:(NSData *)data backData:(void (^)(NSData *))backData
{
    NSURL *urlData = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlData cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSInputStream *inputStream = [NSInputStream inputStreamWithData:data];
    [request setHTTPBodyStream:inputStream];
    NSURLSession *session = [NSURLSession sharedSession];
    [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data == nil) {
            NSLog(@"------99999999%@",error);
            return;
        }
        else{
            backData(data);
        }
        
    }];
}
@end
